using Microsoft.AspNetCore.Mvc;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Application.Services;
using Microsoft.AspNetCore.Authorization;

namespace UniversalAdmin.Api.Controllers;

[ApiController]
[Route("api/v1/[controller]")]
public class PermissionController : ControllerBase
{
    private readonly IPermissionService _permissionService;
    private readonly IRolePermissionService _rolePermissionService;

    public PermissionController(IPermissionService permissionService, IRolePermissionService rolePermissionService)
    {
        _permissionService = permissionService;
        _rolePermissionService = rolePermissionService;
    }

    // 获取所有权限
    [HttpGet]
    [AllowAnonymous] // 允许匿名访问，用于测试
    public async Task<IActionResult> GetAllPermissions()
    {
        try
        {


            var permissions = await _permissionService.GetAllPermissionsAsync();



            return Ok(permissions);
        }
        catch (Exception ex)
        {




            return StatusCode(500, new
            {
                message = "获取权限列表失败",
                error = ex.Message,
                details = ex.StackTrace
            });
        }
    }

    // 获取权限树
    [HttpGet("tree")]
    public async Task<IActionResult> GetPermissionTree()
    {
        var permissionTree = await _permissionService.GetPermissionTreeAsync();
        return Ok(permissionTree);
    }

    // 根据ID获取权限
    [HttpGet("{id}")]
    public async Task<IActionResult> GetPermissionById(Guid id)
    {
        var permission = await _permissionService.GetPermissionByIdAsync(id);
        if (permission == null)
            return NotFound(new { message = "权限不存在" });
        return Ok(permission);
    }

    // 创建权限
    [HttpPost]
    public async Task<IActionResult> CreatePermission([FromBody] CreatePermissionDto dto)
    {
        try
        {
            var permission = await _permissionService.CreatePermissionAsync(dto);
            return CreatedAtAction(nameof(GetPermissionById), new { id = permission.Id }, permission);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    // 更新权限
    [HttpPut("{id}")]
    public async Task<IActionResult> UpdatePermission(Guid id, [FromBody] UpdatePermissionDto dto)
    {
        try
        {
            var permission = await _permissionService.UpdatePermissionAsync(id, dto);
            if (permission == null)
                return NotFound(new { message = "权限不存在" });
            return Ok(permission);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    // 删除权限
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeletePermission(Guid id)
    {
        try
        {
            var success = await _permissionService.DeletePermissionAsync(id);
            if (!success)
                return NotFound(new { message = "权限不存在" });
            return NoContent();
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    // 根据角色获取权限
    [HttpGet("by-role/{roleId}")]
    public async Task<IActionResult> GetPermissionsByRole(Guid roleId)
    {
        var permissions = await _permissionService.GetPermissionsByRoleAsync(roleId);
        return Ok(permissions);
    }

    // 为角色分配权限
    [HttpPost("assign-to-role")]
    public async Task<IActionResult> AssignPermissionsToRole([FromBody] RolePermissionAssignmentDto dto)
    {
        try
        {
            await _rolePermissionService.AssignPermissionsToRoleAsync(dto.RoleId, dto.PermissionIds);
            return Ok(new { message = "权限分配成功" });
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = "权限分配失败", detail = ex.Message });
        }
    }

    // 清空角色权限
    [HttpDelete("by-role/{roleId}")]
    public async Task<IActionResult> ClearRolePermissions(Guid roleId)
    {
        try
        {
            await _rolePermissionService.ClearRolePermissionsAsync(roleId);
            return Ok(new { message = "角色权限已清空" });
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = "清空权限失败", detail = ex.Message });
        }
    }

    // 批量启用/禁用权限
    [HttpPut("batch-status")]
    public async Task<IActionResult> BatchUpdatePermissionStatus([FromBody] BatchPermissionStatusDto dto)
    {
        try
        {
            await _permissionService.BatchUpdateStatusAsync(dto.PermissionIds, dto.IsEnabled);
            return Ok(new { message = "批量更新成功" });
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = "批量更新失败", detail = ex.Message });
        }
    }

    // 获取权限统计信息
    [HttpGet("stats")]
    public async Task<IActionResult> GetPermissionStats()
    {
        var stats = await _permissionService.GetPermissionStatsAsync();
        return Ok(stats);
    }

    // 初始化权限数据
    [HttpPost("init")]
    [AllowAnonymous] // 允许匿名访问
    public async Task<IActionResult> InitializePermissions()
    {
        try
        {
            // 检查是否已有权限数据
            var existingPermissions = await _permissionService.GetAllPermissionsAsync();
            if (existingPermissions.Any())
            {
                return BadRequest(new { message = "权限数据已存在，无需重复初始化" });
            }

            // 创建基础权限
            var permissions = new List<CreatePermissionDto>
            {
                // 用户管理权限
                new("用户查看", "查看用户列表", "user", "read"),
                new("用户创建", "创建新用户", "user", "create"),
                new("用户编辑", "编辑用户信息", "user", "update"),
                new("用户删除", "删除用户", "user", "delete"),
                
                // 角色管理权限
                new("角色查看", "查看角色列表", "role", "read"),
                new("角色创建", "创建新角色", "role", "create"),
                new("角色编辑", "编辑角色信息", "role", "update"),
                new("角色删除", "删除角色", "role", "delete"),
                
                // 权限管理权限
                new("权限查看", "查看权限列表", "permission", "read"),
                new("权限创建", "创建新权限", "permission", "create"),
                new("权限编辑", "编辑权限信息", "permission", "update"),
                new("权限删除", "删除权限", "permission", "delete"),
                
                // 菜单管理权限
                new("菜单查看", "查看菜单列表", "menu", "read"),
                new("菜单创建", "创建新菜单", "menu", "create"),
                new("菜单编辑", "编辑菜单信息", "menu", "update"),
                new("菜单删除", "删除菜单", "menu", "delete"),
                
                // 日志管理权限
                new("日志查看", "查看操作日志", "log", "read"),
                new("日志导出", "导出操作日志", "log", "export"),

                // 文章管理权限
                new("文章查看", "查看文章列表", "article", "read"),
                new("文章创建", "创建新文章", "article", "create"),
                new("文章编辑", "编辑文章信息", "article", "update"),
                new("文章删除", "删除文章", "article", "delete"),

                // 文章分类权限
                new("分类查看", "查看分类列表", "category", "read"),
                new("分类创建", "创建新分类", "category", "create"),
                new("分类编辑", "编辑分类信息", "category", "update"),
                new("分类删除", "删除分类", "category", "delete"),
            };

            var createdPermissions = new List<PermissionDto>();
            foreach (var permission in permissions)
            {
                var createdPermission = await _permissionService.CreatePermissionAsync(permission);
                createdPermissions.Add(createdPermission);
            }

            return Ok(new
            {
                message = "权限数据初始化成功",
                count = createdPermissions.Count,
                permissions = createdPermissions
            });
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = "权限数据初始化失败", error = ex.Message });
        }
    }
}

// 批量权限状态更新DTO
public record BatchPermissionStatusDto(List<Guid> PermissionIds, bool IsEnabled);